package dream_scene

import (
	"go_server/game_server/dao/scene_info_dao"
	"go_server/game_server/dataconfig/config_manager"
	"go_server/game_server/protocol/pb"
	"go_server/game_server/util"
	"go_server/game_server/world_manager"
	"go_server/zinx/ziface"
	"go_server/zinx/znet"
)

type GetDreamSceneBoxStatesApi struct {
	znet.BaseRouter
}

func (*GetDreamSceneBoxStatesApi) Handle(request ziface.IRequest) {
	msg := &pb.GetDreamSceneBoxStatesC2S{}
	if !util.PBParseRet(request, msg) {
		return
	}

	conn := request.GetConnection()
	roleId := ServiceObj.GetRoleId(request)

	if msg.SceneId <= 0 {
		world_manager.WorldMgrObj.SendClientErrMsg(roleId, request, pb.ErrorCodeManager_PARAM_ERROR, nil)
		return
	}

	baseSceneInfo, ok := config_manager.GetStcTableLevelChapter_SheetLevelChapterById(msg.SceneId)
	if !ok || baseSceneInfo.EntType != DREAM_SCENE_EVENT_TYPE {
		world_manager.WorldMgrObj.SendClientErrMsg(roleId, request, pb.ErrorCodeManager_DREARM_SCENE_UNFIND, nil)
		return
	}

	row := scene_info_dao.GetSceneByRoleId(roleId, []string{"scene_info", "box_info"})
	if row == nil {
		world_manager.WorldMgrObj.SendClientErrMsg(roleId, request, pb.ErrorCodeManager_DREARM_SCENE_UNINIT, nil)
		return
	}

	tmpSceneMap := make(map[int32][]int32)
	if row.SceneInfo.Data() != nil {
		tmpSceneMap = row.SceneInfo.Data()
	}

	tmpBoxMap := make(map[int32][]int32)
	if row.BoxInfo.Data() != nil {
		tmpBoxMap = row.BoxInfo.Data()
	}

	sceneInfo, ok := tmpSceneMap[msg.SceneId]
	if !ok {
		world_manager.WorldMgrObj.SendClientErrMsg(roleId, request, pb.ErrorCodeManager_DREARM_SCENE_UNLOCK, nil)
		return
	}

	totalStar := sceneInfo[2] // 当前关卡累计星级

	boxInfo, ok := tmpBoxMap[msg.SceneId]
	if !ok {
		boxInfo = []int32{0, 0, 0}
	}

	for index, limitStar := range baseSceneInfo.StarNum {
		if boxInfo[index] < 2 && totalStar >= limitStar {
			boxInfo[index] = 1 // 可领取
		}
	}

	// 组装返回数据结构
	res := new(pb.GetDreamSceneBoxStatesS2C)
	res.SceneId = msg.SceneId
	res.BoxStates = boxInfo

	conn.SendBuffPBMsg(uint32(pb.ProtocolManager_GetDreamSceneBoxStates), res)

}
